﻿(function($){
    $.extend({
        WebGrid: function(config) {
            if (!(this instanceof $.WebGrid)){
                return new $.WebGrid(config);
            }
            var grid = this,
                data, rows, rowcount,
                div_headerMain, div_header, 
                div_body, div_pager, div_totalRowMain, div_totalRow,
                table_header, table_body, table_totalRow,
                header_first_row_tds, body_first_row_tds, totalRow_first_row_tds,
                headerRowHeight = 25, totalRowHeight = 25,
                headerHeight = 25, pagerHeight = 25,
                contentWidth, contentHeight,
                m = Math.random().toString().replace(".",""),
                refresh_reason_s = { load: 0, newPage: 1, sort: 2, other: 3 },
                refresh_reason = refresh_reason_s.other,
                //用于记录当前页数，防止刷新页面时总是在第一页
                cookie = function(key, value) {
                    if (arguments.length == 1) {
                        var cookies = document.cookie.split(";");
                        for (var i = 0; i < cookies.length; i++) {
                            if ($.trim(cookies[i].split("=")[0]) == key) {
                                return unescape($.trim(cookies[i].split("=")[1]));
                            }
                        }
                        return null;
                    }
                    else {
                        document.cookie = key + "=" + escape(value);
                    }
                },
                //对config初始化，设定默认值
                c = (function(c) {
                    if (c && c.contentId) {
                        var c_pi = parseInt(cookie("pageindex_" + c.contentId));
                        c.url = c.url || "";
                        c.dataSource = c.dataSource || null;
                        c.params = c.params || {};
                        c.width = c.width || "";
                        c.height = c.height || "";
                        c.root = c.root || "DataTable";
                        c.total = c.total || "RowCount";
                        c.rowHeight = c.rowHeight || 23;
                        c.pageSize = c.pageSize || 10;
                        c.fontSize = c.fontSize || 13;
                        c.keyField = c.keyField || "";
                        c.sortName = c.sortName || "";
                        c.sortOrder = c.sortOrder || "asc";
                        c.linkEditDefaultText = c.linkEditDefaultText ? c.linkEditDefaultText : "单击编辑";
                        c.stopTdTrEvent = typeof c.stopTdTrEvent == "boolean" ? c.stopTdTrEvent : true;
                        c.mustSelect = typeof c.mustSelect == "boolean" ? c.mustSelect : false;
                        c.showTotalRow = typeof c.showTotalRow == "boolean" ? c.showTotalRow : false;
                        c.headerFontBold = typeof c.headerFontBold == "boolean" ? c.headerFontBold : true;
                        c.colResizAble = typeof c.colResizAble == "boolean" ? c.colResizAble : true;
                        c.rowMultiLine = typeof c.rowMultiLine == "boolean" ? c.rowMultiLine : false;
                        c.autoHeight = typeof c.autoHeight == "boolean" ? c.autoHeight : false;
                        c.sortAble = typeof c.sortAble == "boolean" ? c.sortAble : false;
                        c.remoteSort = typeof c.remoteSort == "boolean" ? c.remoteSort : true;
                        c.dblClickToEdit = typeof c.dblClickToEdit == "boolean" ? c.dblClickToEdit : true;
                        c.pager = typeof c.pager == "boolean" ? c.pager : true;
                        c.showPagerInfo = typeof c.showPagerInfo == "boolean" ? c.showPagerInfo : true;
                        c.autoRefresh = typeof c.autoRefresh == "boolean" ? c.autoRefresh : true;
                        c.autoLoad = typeof c.autoLoad == "boolean" ? c.autoLoad : true;
                        c.multiSelect = typeof c.multiSelect == "boolean" ? c.multiSelect : true;
                        c.isCookie = typeof c.isCookie == "boolean" ? c.isCookie : true;
                        c.showCheckBox = typeof c.showCheckBox == "boolean" ? c.showCheckBox : false;
                        c.autoSave = typeof c.autoSave == "boolean" ? c.autoSave : false;
                        c.is3D = typeof c.is3D == "boolean" ? c.is3D : false;
                        c.pageIndex = c.isCookie ? c_pi && c_pi >= 1 ? c_pi : 1 : (c.pageIndex || 1);
                        c.borderWidth3D = c.borderWidth3D == 1 || c.borderWidth3D == 2 ? c.borderWidth3D : 1;
                        
                        c.colors = c.colors || {};
                        c.colors.borderColor = c.colors.borderColor || "Gray";
                        c.colors.headerBgColor = c.colors.headerBgColor || "#D4D0C8";
                        c.colors.evenRowBgColor = c.colors.evenRowBgColor || "White";
                        c.colors.oddRowBgColor = c.colors.oddRowBgColor || "#F0EEEC";
                        c.colors.pagerBgColor = c.colors.pagerBgColor || "#D4D0C8";
                        c.colors.scrollbarColor = c.colors.scrollbarColor || "#D4D0C8";
                        c.colors.selectedRowColor = c.colors.selectedRowColor || "#D4D0C8";
                        c.colors.rowHighLightColor = c.colors.rowHighLightColor || "#D4D0C8";
                        
                        c.columns = c.columns || [];
                        (function(cols_){
                            if (cols_){
                                for (var i = 0; i < cols_.length; i++) {
                                    var col = cols_[i];
                                    col.type = col.type || "data";
                                    col.title = col.title ? col.title == "" ? "&nbsp;" : col.title : "&nbsp;";
                                    col.text = col.text ? col.text == "" ? "&nbsp;" : col.text : "&nbsp;";
                                    col.visible = typeof col.visible == "boolean" ? col.visible : true;
                                    col.editable = typeof col.editable == "boolean" ? col.editable : false;
                                    col.sortAble = typeof col.sortAble == "boolean" ? col.sortAble : true;
                                    col.align = col.align || "left";
                                    col.defaultVal = col.defaultVal || "";
                                    col.dataType = col.dataType || "string";
                                    
                                    if (!col.columns || col.columns.length == 0){
                                        col.editer = col.editer || {};
                                        col.editer.type = col.editer.type || "text";
                                        col.editer.valField = col.editer.valField || col.editer.txtField || "";
                                        col.editer.txtField = col.editer.txtField || col.editer.valField || "";
                                        col.editer.items = col.editer.items || [];
                                    }
                                    
                                    arguments.callee(col.columns);
                                }
                            }
                        })(c.columns);
                    }
                    else {
                        c = null;
                    }
                    
                    grid.config = c;
                    return c;

                })(config),
                realColumns_Info = (function(){
                    var l_ = 0, arr = [], arr_ = [];
                    (function(cols_){
                        var lev = l_++;
                        for(var i=0;i<cols_.length;i++){
                            var col_ = cols_[i];
                            col_.leve = lev;
                            if (!col_.columns || col_.columns.length == 0){
                                arr.push(col_);
                                if (i == cols_.length - 1){
                                    l_ = l_ - 1 > 0 ? l_ - 1 : 0;
                                }
                            }
                            else{
                                arguments.callee(col_.columns);
                            }
                        }
                    })(c.columns);
                    
                    (function(cols_){
                        for(var i=0;i<cols_.length;i++){
                            var col_ = cols_[i];
                            if (!arr_[col_.leve]){
                                arr_[col_.leve] = [];
                            }
                            arr_[col_.leve].push(col_);
                            if (col_.columns && col_.columns.length > 0){
                                arguments.callee(col_.columns);
                            }
                        }
                    })(c.columns);
                    
                    for(var i=0;i<arr.length;i++){
                        arr[i].__getIndex__ = function(){
                            var index_ = i;
                            return function(){
                                return index_;
                            }
                        }();
                    }
                    grid.realColumns = arr;
                    return {
                        cols: arr,
                        rows: arr_
                    };
                })(),
                headerHeight = headerRowHeight * realColumns_Info.rows.length,
                sortColdataType = (function(cols_){
                    for(var i=0;i<cols_.length;i++){
                        if (cols_[i].field == c.sortName){
                            return cols_[i].dataType || "string";
                        }
                    }
                    return "string";
                })(realColumns_Info.cols),
                content = (function(c){
                    var w_ = 0,
                        h_ = 0,
                        cont = $("#" + c.contentId);
                       
                    if (c.width != ""){
                        cont.css({ "width": c.width + "px" });
                    }
                    if (c.height != ""){
                        cont.css({ "height": (c.autoHeight ? "auto" : c.height + "px") });
                    }
                    w_ = cont[0].clientWidth - (c.is3D ? c.borderWidth3D * 2 : 2);
                    h_ = cont[0].clientHeight - (c.is3D ? c.borderWidth3D * 2 : 2) - (c.showTotalRow ? 3 : 2);
                    contentWidth = w_ < 0 ? 0 : w_;
                    contentHeight = h_ < 0 ? 0 : h_;
                    
                    return cont;
                })(c),
                //阻止事件冒泡
                stopBubble = function(e){
                    if (e && e.stopPropagation){
                        e.stopPropagation();
                    }
                    else{
                        event.cancelBubble = true;
                    }
                },
                insertArrayAt = function(arr_, obj_, index_){
                    var arr_1 = arr_.slice(0, index_),
                        arr_2 = arr_.slice(index_);
                    
                    delete arr_;
                    if (obj_ instanceof Array){
                        return arr_1.concat(obj_, arr_2);
                    }
                    else{
                        arr_1.push(obj_);
                        return arr_1.concat(arr_2);
                    }
                },
                removeArrayAt = function(arr_, index_){
                    var arr_1 = arr_.slice(0, index_),
                        arr_2 = arr_.slice(index_);
                    
                    delete arr_;
                    arr_2.shift();
                    return arr_1.concat(arr_2);
                },
                //从服务端获取数据
                getData = function(c, arr){
                    var createData = function(rows, count){
                        var obj = {};
                        obj[c.root] = rows || [];
                        obj[c.total] = count || 0;
                        return obj;
                    };
                    
                    if (arr instanceof Array){
                        data = createData(arr);
                    }
                    else{
                        (function(){
                            if (c.pager) {
                                if (c.sortAble && c.remoteSort) {
                                    c.params.sortName = c.sortName;
                                    c.params.sortOrder = c.sortOrder;
                                }
                                c.params.pageIndex = c.pageIndex;
                                c.params.pageSize = c.pageSize;
                            }
                            else {
                                if (c.sortAble && c.remoteSort) {
                                    c.params.sortName = c.sortName;
                                    c.params.sortOrder = c.sortOrder;
                                }
                            }
                        })();
                        
                        if (c.dataSource){
                            data = createData(c.dataSource);
                        }
                        else {
                            var ajax_r = function(){
                                var obj = createData();
                                $.ajax({
                                    url: c.url,
                                    async: false,
                                    type: "post",
                                    data: c.params,
                                    dataType: "text",
                                    success: function(txt) {
                                        try {
                                            if (window.JSON && window.JSON.parse){
                                                try{
                                                    obj = window.JSON.parse(txt);
                                                }
                                                catch(e){
                                                    obj = window.eval("(" + txt + ")");
                                                }
                                            }
                                            else{
                                                obj = window.eval("(" + txt + ")");
                                            }
                                        }
                                        catch(e){
                                            
                                        }
                                    }
                                });
                                return obj;
                            };
                            
                            data = refresh_reason == refresh_reason_s.sort ? 
                                c.remoteSort ? ajax_r() : data 
                                    : ajax_r();
                        }
                        
                        if (!c.remoteSort){
                            data[c.root].sort(getSortFunction(c, sortColdataType));
                        }
                    }
                    
                    rows = data[c.root];
                    rowcount = data[c.total];
                    grid.dataRows = rows;
                },
                getLen = function(){
                    var l = 0,
                        cols_ = realColumns_Info.cols;
                    for(var i=0;i<cols_.length;i++){
                        var col_ = cols_[i];
                        if (!col_.width || /^\d+%$/.test(col_.width)){
                            return (contentWidth - 17 < 0 ? 0 : contentWidth - 17) + "px";
                        }
                        else{
                            l += col_.width + 1;
                        }
                    }
                    if (c.showCheckBox){
                        l += 26;
                    }
                    return l + "px";
                },
                getSortFunction = function(c, t){
                    var o = c.sortOrder,
                        f = c.sortName,
                        t = t || "string";
                    
                    return function(a, b){
                        try {
                            switch(t){
                                case "string":
                                    return o == "asc" ? a[f].localeCompare(b[f]) : b[f].localeCompare(a[f]);
                                case "number":
                                    return o == "asc" ? a[f] - b[f] : b[f] - a[f];
                                case "date":
                                    var r = /\d{4}[\-/]\d{1,2}[\-/]\d{1,2}(\s\d{1,2}:\d{1,2}:\d{1,2})?/;
                                    var dateStrToInt = function(s){
                                        var ss = s.split(/[\-/\s:]/),
                                            to_2 = function(s){
                                                s = parseInt(s);
                                                return s < 10 ? "0" + s : s;
                                            };
                                        s = "";
                                        for(var i=0;i<ss.length;i++){
                                            s += to_2(ss[i]);
                                        }
                                        return parseInt(s);
                                    };
                                    if (r.test(a[f]) && r.test(b[f])){
                                        return o == "asc" ? dateStrToInt(a[f]) - dateStrToInt(b[f]) : dateStrToInt(b[f]) - dateStrToInt(a[f]);
                                    }
                                    else{
                                        return o == "asc" ? a[f].localeCompare(b[f]) : b[f].localeCompare(a[f]);
                                    }
                                default:
                                    return 0;
                            }
                        }
                        catch(e){
                            return 0;
                        }
                    };
                },
                objToXML = function(o){
                    var doc = null,
                        xmlS = null;
                    
                    try {
                        if (window.ActiveXObject) {
                            doc = new ActiveXObject("Microsoft.XMLDOM");
                        }
                        else {
                            doc = document.implementation.createDocument("","",null);
                        }
                        
                        if (doc){
                            var rootN = doc.createElement("rows");
                            if (o instanceof Array && o.length > 0){
                                for(var i=0;i<o.length;i++){
                                    var rowN = doc.createElement("row");
                                    rowN.setAttribute("index", o[i].index);
                                    for(var it in o[i].data){
                                        var obj = o[i].data[it],
                                            val = obj.val && obj.changed ? o[i].data[it]["val"] : obj,
                                            changed = obj.val && obj.changed && o[i].data[it]["changed"] ? "1" : null,
                                            colN = doc.createElement("col");
                                        
                                        colN.setAttribute("field", it);
                                        colN.setAttribute("value", val);
                                        if (changed){
                                            colN.setAttribute("changed", changed);
                                        }
                                        rowN.appendChild(colN);
                                    }
                                    rootN.appendChild(rowN);
                                }
                            }
                            doc.appendChild(rootN);
                            
                            if (window.ActiveXObject) {
                                xmlS = doc.xml;
                            }
                            else {
                                xmlS = (new XMLSerializer()).serializeToString(doc);
                            }
                         }
                    }
                    catch(e) {
                        
                    }
                    
                    return { xml: doc, xmlString: xmlS };
                },
                encodeHtml = function(h_){
                    return h_ ? h_.replace(/</g, "&lt;").replace(/>/g, "&gt;") : "";
                },
                decodeHtml = function(h_){
                    return h_ ? h_.replace(/&lt;/g, "<").replace(/&gt;/g, ">") : "";
                },
                _nToBr = function(t_){
                    return t_ ? t_.replace(/(\\n)|(\n)/g, c.rowMultiLine ? "</br>" : "").replace(/\s/g, "&nbsp;") : "";
                },
                brTo_n = function(h_){
                    return h_ ? h_.replace(/<\/br>/ig, "\n") : "";
                },
                createContent = function(c){
                    var bodyHeight = c.autoHeight ? "auto" 
                            : (c.pager ? 
                                c.showTotalRow ? contentHeight - headerHeight - pagerHeight - totalRowHeight : contentHeight - headerHeight - pagerHeight 
                                    : c.showTotalRow ? contentHeight - headerHeight - totalRowHeight : contentHeight - headerHeight) + "px",
                        arr = [],
                        body_border_bottom = c.pager || c.showTotalRow ? "border-bottom:solid 1px " + c.colors.borderColor + ";" : "",
                        totalRowMain_border_bottom = c.pager ? "border-bottom:solid 1px " + c.colors.borderColor + ";" : "",
                        border = c.is3D ? "border-top:solid " + c.borderWidth3D + "px #D4D0C8;border-left:solid " + c.borderWidth3D + "px #D4D0C8;border-right:solid " + c.borderWidth3D + "px #404040;border-bottom:solid " + c.borderWidth3D + "px #404040;" : "border:solid 1px " + c.colors.borderColor + ";";
                    
                    arr.push("<div id='div_headerMain_", m, "' style='text-align:left;background-color:", c.colors.headerBgColor, ";", border, "border-bottom:solid 1px ", c.colors.borderColor, ";overflow:hidden;height:", headerHeight, "px;width:", contentWidth, "px;font-size:", c.fontSize, "px;'>");
                    arr.push("<div id='div_header_", m, "' style='border-right:none;overflow:hidden;height:", headerHeight, "px;'></div></div>");
                    arr.push("<div id='div_body_", m, "' style='text-align:left;scrollbar-dark-shadow-color:", c.colors.scrollbarColor, ";scrollbar-shadow-color:", c.colors.scrollbarColor, ";scrollbar-base-color:", c.colors.scrollbarColor, ";", border, body_border_bottom, ";border-top:none;overflow:auto;width:", contentWidth, "px;height:", bodyHeight, ";font-size:", c.fontSize, "px;'></div>");
                    if (c.showTotalRow){
                        arr.push("<div id='div_totalRowMain_", m, "' style='text-align:left;", border, totalRowMain_border_bottom, "border-top:none;overflow:hidden;height:", totalRowHeight, "px;width:", contentWidth, "px;'>");
                        arr.push("<div id='div_totalRow_", m, "' style='border:none;overflow:hidden;height:", totalRowHeight, "px;font-size:", c.fontSize, "px;'></div></div>");
                    }
                    if (c.pager) {
                        arr.push("<div id='div_pager_", m, "' style='background-color:", c.colors.pagerBgColor, ";", border, "border-top:none;overflow:hidden;width:", contentWidth, "px;height:", pagerHeight, "px;font-size:", c.fontSize, "px;'></div>");
                    }
                    content.html(arr.join(""));
                    
                    div_headerMain = $("#div_headerMain_" + m);
                    div_header = $("#div_header_" + m);
                    div_body = $("#div_body_" + m);
                    div_pager = $("#div_pager_" + m);
                    div_totalRowMain = $("#div_totalRowMain_" + m)
                    div_totalRow = $("#div_totalRow_" + m);
                },
                createHeader = function(c){
                    var o = {}, asc_ = "▲",
                        desc_ = "▼", arr = [],
                        rows_ = realColumns_Info.rows,
                        cols_ = realColumns_Info.cols;
                    
                    arr.push("<table id='table_header_", m, "' cellpadding='0px' cellspacing='0px' style='margin-top:-1px;width:", getLen(), ";background-color:Gray;table-layout:fixed;border-collapse:collapse;height:", headerHeight, "px;'><tr style='height:0px;'>");
                    if (c.showCheckBox){
                        arr.push("<td field='' style='border:solid 1px;border-left:none;border-top:none;border-bottom:none;width:25px;'></td>");
                    }
                    for(var i=0;i<cols_.length;i++){
                        var col_ = cols_[i],
                            width = col_.width ? /^\d+%$/.test(col_.width) ? col_.width : col_.width + "px" : "auto",
                            borderleft = c.showCheckBox ? "" : i == 0 ? "border-left:none;" : "";
                        
                        arr.push("<td field='' colindex='", i, "' style='border:solid 1px;", borderleft, "border-top:none;border-bottom:none;width:", width, ";'></td>");
                    }
                    arr.push("</tr>");
                    for(var i=0;i<rows_.length;i++){
                        var index_ = 0,
                            cols_row = rows_[i],
                            font_bold = c.headerFontBold ? "font-weight:bold;" : "";
                        
                        arr.push("<tr style='cursor:default;'>");
                        if (c.showCheckBox && i == 0){
                            arr.push("<td rowspan='", rows_.length, "' field='' style='width:25px;border:solid 1px ", c.colors.borderColor, ";border-left:none;border-top:none;border-bottom:none;background-color:", c.colors.headerBgColor, ";text-align:center;'><input id='checkall_", m, "' type='checkbox'/></td>");
                        }
                        for (var j = 0; j < cols_row.length; j++) {
                            var col_ = cols_row[j],
                                t_height = 24,
                                col_span = (function(){
                                    var i_s = 0;
                                    (function(col){
                                        if (!col.columns || col.columns.length == 0){
                                            i_s++;
                                        }
                                        else{
                                            for(var i=0;i<col.columns.length;i++){
                                                arguments.callee(col.columns[i]);
                                            }
                                        }
                                    })(col_);
                                    return i_s;
                                })(),
                                index_ = col_.__getIndex__ ? col_.__getIndex__() : 0,
                                rowspan = !col_.columns || col_.columns.length == 0 ? " rowspan='" + (rows_.length - i) + "' " : "",
                                colspan = col_.columns && col_.columns.length > 0 ? " colspan='" + col_span + "' " : "",
                                cursor = col_.sortAble ? col_.field ? "cursor:pointer;" : "" : "",
                                field = col_.field ? col_.field : "",
                                title = i == rows_.length - 1 ? col_.sortAble ? c.sortAble ? col_.type.toLowerCase() == "data" ? " title='单击进行排序' " : "" : "" : "" : "",
                                borderleft = c.showCheckBox ? "" : j == 0 ? "border-left:none;" : "",
                                bordertop = i == 0 ? "border-top:none;" : "",
                                display = col_.visible ? "" : "display:none;",
                                arrow = c.sortAble ? col_.field == c.sortName ? c.sortOrder == "" ? "" : c.sortOrder.toLowerCase() == "asc" ? asc_ : desc_ : "" : "",
                                div_resize = c.colResizAble && (!col_.columns || col_.columns.length == 0) ?  "<div title='拖动可改变列宽' class='resize_" + m + "' style='float:right;margin-right:0px;height:" + t_height + "px;width:3px;border:0px;cursor:e-resize;'></div>" : "";
                            
                            arr.push("<td ", rowspan, colspan, " colindex='", index_, "' field='", field, "' valign='center' nowrap='nowrap' style='border:solid 1px ", c.colors.borderColor, ";", borderleft, bordertop, display, "border-bottom:none;background-color:", c.colors.headerBgColor, 
                                ";text-align:center;margin:0px;", font_bold, "'><div style='vertical-align:middle;width:100%;height:", t_height, "px;'><div class='title_", m, "' style='overflow:hidden;padding-top:5px;float:left;", font_bold, "font-size:", c.fontSize,
                                "px;'><span title_='", col_.title, "' sortAble='", (col_.sortAble ? "1" : "0"), "' order='", c.sortOrder, "' field='", field, "' ", title, " style='", cursor, "text-overflow:ellipsis;white-space: nowrap;'>", col_.title , arrow, "</span></div>", div_resize, "</div></td>");
                        }
                        arr.push("</tr>");
                    }
                    arr.push("</table>");
                    table_header = div_header.html(arr.join("")).find("#table_header_" + m);
                    header_first_row_tds = table_header.find("tr:first td");
                    
                    //点击表头排序
                    var title_div = $(".title_" + m).css("width", function(i, v){
                            var w_ = this.parentNode.parentNode.clientWidth;
                            this.parentNode.style.width = w_ + "px";
                            return w_ > 4 ? w_ - 4 : 0;
                        }),
                        table_header_td_span = table_header.find("tr td[field!=''] span[sortAble='1']");
                    
                    table_header_td_span.click(function(){
                        if (c.sortAble){
                            var arrow = "",
                                sortColdataType = this.getAttribute("dataType");
                            
                            c.sortName = this.getAttribute("field");
                            switch(this.getAttribute("order")){
                                case "":
                                case "desc":
                                    c.sortOrder = "asc";
                                    arrow = asc_;
                                    break;
                                case "asc":
                                    c.sortOrder = "desc";
                                    arrow = desc_;
                                    break;
                                default:
                                    return;
                            }
                            table_header_td_span.attr("order", "");
                            $(this).attr("order", c.sortOrder);
                            
                            refresh_reason = refresh_reason_s.sort;
                            if (c.remoteSort) {
                                grid.refresh();
                            }
                            else {
                                data[c.root].sort(getSortFunction(c, sortColdataType));
                                grid.refresh();
                            }
                            
                            table_header_td_span.each(function(i, o){
                                $(o).html(o.getAttribute("title_"));
                            });
                            $(this).html(this.getAttribute("title_") + arrow);
                        }
                    });
                    
                    //全选全不选
                    var checkall = $("#checkall_" + m);
                    checkall.click(function(){
                        var table_body = $("#table_body_" + m),
                            checkone = $(".checkone_" + m);
                        if (c.multiSelect){
                            checkone.attr({ "checked": this.checked });
                            if (this.checked){
                                table_body.find(".tr_" + m).css({ "background-color": c.colors.selectedRowColor }).attr({ "selected_": this.checked ? "1" : "0" });
                            }
                            else {
                                table_body.find(".tr_" + m + ":even").css({ "background-color": c.colors.evenRowBgColor }).attr({ "selected_": "0"});
                                table_body.find(".tr_" + m + ":odd").css({ "background-color": c.colors.oddRowBgColor }).attr({ "selected_": "0"});
                            }
                        }
                        else{
                            $(this).attr("checked",false);
                        }
                    });
                    
                    //拖动改变列的宽度
                    var td_ = null,
                        index_ = 0,
                        resize_ = $(".resize_" + m);
                    
                    resize_.mousedown(function(e){
                        td_ = $(this).parent().parent();
                        index_ = parseInt(td_.attr("colindex"));
                        index_ = c.showCheckBox ? index_ + 1 : index_;
                        
                        header_first_row_tds.each(function(i, o_){
                            var c_width = grid.loaded ? o_.style.pixelWidth : o_.clientWidth;
                            $(body_first_row_tds[i]).css("width", c_width + "px");
                            $(totalRow_first_row_tds[i]).css("width", c_width + "px");
                            $(o_).css("width", c_width + "px");
                        });
                        o.X = e.clientX;
                        o.W = td_[0].offsetWidth;
                        o.BW = table_header[0].offsetWidth;
                        
                        if (this.setCapture){
                            this.setCapture();
                        }
                        else if (window.captureEvents){
                            window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
                        }
                    }).mouseup(function(e){
                        o.X = 0;
                        header_first_row_tds.each(function(i, o_){
                            var col_index = o_.getAttribute("colindex");
                            if (col_index){
                                realColumns_Info.cols[col_index].width = grid.loaded ? o_.style.pixelWidth : o_.clientWidth;
                            }
                        });
                        title_div.css("width", function(i, v){
                            var w_ = this.parentNode.parentNode.clientWidth;
                            this.parentNode.style.width = w_ + "px";
                            return w_ > 4 ? w_ - 4 : 0;
                        });
                        
                        if (this.releaseCapture){
                            this.releaseCapture();
                        }
                        else if (window.captureEvents){
                            window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
                            this.onmousemove = null;
                            this.onmouseup = null;
                        }
                    }).mousemove(function(e){
                        if(o.X){
                            var tdw = o.W + e.clientX - o.X;
                            var bw = o.BW + e.clientX - o.X;
                            if(table_body && tdw > 10) {
                                $(header_first_row_tds[index_]).css("width", tdw + "px");
	                            table_header.css({ "width": bw + "px" });
	                            
	                            $(body_first_row_tds[index_]).css("width", tdw + "px");
	                            table_body.css({ "width": bw + "px" });
	                            
	                            $(totalRow_first_row_tds[index_]).css("width", tdw + "px");
	                            table_totalRow.css({ "width": bw + "px" });
                                setHeader();
	                        }
	                        
	                        title_div.css("width", function(i, v){
                                var w_ = this.parentNode.parentNode.clientWidth;
                                this.parentNode.style.width = w_ + "px";
                                return w_ > 4 ? w_ - 4 : 0;
                            });
	                    }
                    });
                },
                createRow = function(dataRow_, index_, setWidth_, addNew_){
                    var arr = [],
                        cols_ = realColumns_Info.cols,
                        addNewRow_ = addNew_ ? " new='new' " : "",
                        bgColor = index_ % 2 == 0 ? c.colors.evenRowBgColor : c.colors.oddRowBgColor;
                    
                    arr.push("<tr class='tr_", m, "' ", addNewRow_, " style='height:", c.rowHeight, "px;background-color:", bgColor, ";'>");
                    if (c.showCheckBox){
                        arr.push("<td style='width:25px;brder-top:none;border-left:none;border-bottom:dashed 1px ", c.colors.borderColor, ";border-right:dashed 1px ", c.colors.borderColor, ";text-align:center;'><input class='checkone_", m, "' type='checkbox'/></td>");
                    }
                    for (var i = 0; i < cols_.length; i++) {
                        var title = "",
                            valign_ = "",
                            str = "&nbsp;",
                            col_ = cols_[i],
                            type_ = col_.type.toLowerCase(),
                            cellType = null,
                            display = col_.visible ? "" : "display:none;",
                            editable = col_.editable ? "" : " disabled='disabled' ";
                        
                        switch (type_) {
                            case "data":
                            case "linkedit":
                                var v_ = dataRow_[col_.field],
                                    style_ = type_ == "linkedit" && !c.rowMultiLine ? "white-space:nowrap;" : "",
                                    tag_ = type_ == "data" ? c.rowMultiLine ? "div" : "nobr" : "a",
                                    attrs_ = type_ == "data" ? " class='cont_" + m + "' " : " href='javascript:void(0);' class='grid_action_" + i + "_" + m + "' ",
                                    val = v_ ? v_.replace(/\\n/g, "\n") : "";
                                
                                cellType = "data";
                                val = val == "" ? col_.defaultVal == "" ? "" : col_.defaultVal : val;
                                var txt = val == "" ? 
                                    col_.defaultVal == "" ? 
                                        (type_ == "data" ? "&nbsp;" : c.linkEditDefaultText)
                                            : col_.defaultVal 
                                        : col_.format ?
                                            col_.format(val,
                                                _nToBr(encodeHtml(val.replace(/&/g, "&amp;"))),
                                                _nToBr(val.replace(/&/g, "&amp;")),
                                                _nToBr(encodeHtml(val).replace(/&/g, "&amp;"))
                                            ) 
                                            : _nToBr(encodeHtml(val.replace(/&/g, "&amp;")));
                                
                                str = "<" + tag_ + attrs_ + " tag='tag_" + m + "' style='" + style_ + "' val='" + escape(val) + "'>" + txt + "</" + tag_ +">";
                                title = " t='t' ";
                                break;
                            case "checkbox":
                                str = "<input var='0' class='grid_ckb_" + m + "' " + editable + " type='checkbox'/>";
                                if (col_.format && col_.format(dataRow_[col_.field], dataRow_[col_.field], dataRow_[col_.field], dataRow_[col_.field])){
                                    str = "<input val='1' class='grid_ckb_" + m + "' " + editable + " checked='checked' type='checkbox'/>";
                                }
                                break;
                            case "button":
                                str = "<input class='grid_action_" + i + "_" + m + "' type='button' value='" + col_.text + "'/>";
                                break;
                            case "linkbutton":
                                str = "<a class='grid_action_" + i + "_" + m + "' href='javascript:void(0);' style='white-space:nowrap;'>" + col_.text + "</a>";
                                break;
                            default:
                                break;
                        }
                        
                        var width = setWidth_ ? "width:" + (col_.width ? /^\d+%$/.test(col_.width) ? col_.width : col_.width + "px" : "auto") : "width:auto",
                            wrap_ = c.rowMultiLine ? "" : " noWrap='noWrap' ",
                            txt_style = c.rowMultiLine ? "word-wrap:break-word;" : "text-overflow:ellipsis;";
                        
                        arr.push("<td class='td_", m, "' field='", col_.field, "' cellType='" + cellType + "' colindex='", i, "' ", wrap_, title, valign_,
                            "style='overflow:hidden;", txt_style, width, ";brder-top:none;border-left:none;border-bottom:dashed 1px ",c.colors.borderColor,
                            ";border-right:dashed 1px ", c.colors.borderColor, ";text-align:", col_.align, ";", display, "'>", str, "</td>");
                    }
                    arr.push("</tr>");
                    return arr.join("")
                },
                setRows_ = function(){
                    $("#table_body_" + m + " tr:even").css("background-color", c.colors.evenRowBgColor);
                    $("#table_body_" + m + " tr:odd").css("background-color", c.colors.oddRowBgColor);
                },
                createBody = function(c){
                    var tempColor,
                        arr = [],
                        cols_ = realColumns_Info.cols;
                    
                    if (rows.length > 0){
                        arr.push("<table id='table_body_", m, "' cellpadding='0px' cellspacing='0px' border='0px' style='width:", getLen(), ";border:none;table-layout:fixed;border-collapse:collapse;empty-cells:show;'>");
                        for (var i = 0; i < rows.length; i++) {
                            arr.push(createRow(rows[i], i, i == 0, false));
                        }
                        arr.push("</table>");
                    }
                    else{
                        arr.push("<table id='table_body_", m, "' cellpadding='0px' cellspacing='0px' border='0px' style='width:", getLen(), ";border:none;table-layout:fixed;'><tr>");
                        if (c.showCheckBox){
                            arr.push("<td style='width:25px;border:none;border-right:1px;height:1px;'></td>");
                        }
                        for (var i = 0; i < cols_.length; i++) {
                            var col_ = cols_[i],
                                width = "width:" + (col_.width ? /^\d+%$/.test(col_.width) ? col_.width : col_.width + "px" : "auto");
                            arr.push("<td style='", width, ";border:none;border-right:1px;height:1px;'></td>");
                        }
                        arr.push("</tr></table>");
                    }
                    table_body = div_body.html(arr.join("")).find("#table_body_" + m);
                    body_first_row_tds = table_body.find("tr:first td");
                    if (c.autoHeight) {
                        div_body.css("height", (table_body[0].clientHeight + 17) + "px");
                    }
                    
                    var grid_ckb = $(".grid_ckb_" + m),
                        pagecount = parseInt(rowcount % c.pageSize == 0 ? (rowcount / c.pageSize > 0 ? rowcount / c.pageSize : 1) : rowcount / c.pageSize + 1);
                    
                    c.pageIndex = c.pageIndex > pagecount ? pagecount : c.pageIndex;
                    grid.pagerInfo = { pageIndex: c.pageIndex, pageSize: c.pageSize, rowCount: rowcount, pageCount: pagecount };
                    
                    //单击行选中...,鼠标移动效果
                    table_body.find(".tr_" + m).die()
                    .live("click", function(){
                        var checkone = $(".checkone_" + m),
                            isSelected = $(this).attr("selected_"),
                            checkb = $(this).find("td:first :checkbox:first");
                        
                        if (c.multiSelect){
                            var color = !isSelected || isSelected == "0" ? c.colors.selectedRowColor : this.rowIndex % 2 == 0 ? c.colors.evenRowBgColor : c.colors.oddRowBgColor,
                                selected = !isSelected || isSelected == "0" ? "1" : "0";
                            $(this).css({ "background-color": color }).css({ "background-color": color });
                            $(this).attr({ "selected_": selected });
                            checkb.attr({ "checked": selected == "1" });
                        }
                        else{
                            var selected_ = $(this).attr("selected_") == "1";
                            if (c.mustSelect){
                                checkone.attr("checked", false);
                                table_body.find("tr:even").css({ "background-color": c.colors.evenRowBgColor }).attr({ "selected_": "0"});
                                table_body.find("tr:odd").css({ "background-color": c.colors.oddRowBgColor }).attr({ "selected_": "0"});
                                $(this).attr({ "selected_": "1" });
                            }
                            else{
                                checkone.not(checkb).attr("checked", false);
                                table_body.find("tr:even").css({ "background-color": c.colors.evenRowBgColor }).not(this).attr({ "selected_": "0"});
                                table_body.find("tr:odd").css({ "background-color": c.colors.oddRowBgColor }).not(this).attr({ "selected_": "0"});
                                $(this).attr({ "selected_": (selected_ ? "0" : "1") });
                            }
                            
                            selected_ = $(this).attr("selected_") == "1";
                            $(this).css({ "background-color": selected_ ? c.colors.selectedRowColor : $(this).css("background-color") });
                            checkb.attr({ "checked": selected_ });
                        }
                        tempColor = $(this).css("background-color");
                        
                        if (grid.currentRowIndex != this.rowIndex){
                            grid.currentRowIndex = this.rowIndex;
                            if (c.rowSelected && c.rowSelected instanceof Function){
                                c.rowSelected.call(grid, { index: this.rowIndex, webGrid: grid, data: rows[this.rowIndex] });
                            }
                        }
                    }).live("mouseover", function(){
                        if (rows.length > 0) {
                            tempColor = $(this).css("background-color");
                            $(this).css({ "background-color": c.colors.rowHighLightColor });
                        }
                    }).live("mouseout", function(){
                        if (rows.length > 0) {
                            $(this).css({ "background-color": tempColor });
                        }
                    }).find("td[t='t']").attr("title", function(i, v){
                        return decodeHtml(unescape($(this).children(":first").attr("val")));
                    });
                    
                    //绑定行事件
                    if (c.onrow){
                        for(var fun in c.onrow){
                            table_body.find("tr").live(fun, function(){
                                if (c.onrow[fun] instanceof Function){
                                    c.onrow[fun].call(grid, { index: this.rowIndex, webGrid: grid, data: rows[this.rowIndex] });
                                }
                            });
                        }
                    }
                    
                    //给按钮、链接、复选框列绑定事件
                    if (realColumns_Info) {
                        var cols_ = realColumns_Info.cols;
                        for(var i=0; i< cols_.length; i++){
                            var col_ = cols_[i];
                            switch (col_.type.toLowerCase()) {
                                case "button":
                                case "linkbutton":
                                case "linkedit":
                                    (function(col, g_act){
                                        var type_ = col_.type.toLowerCase();
                                        if (col.callback && col.callback instanceof Function) {
                                            g_act.die().live("click", function(){
                                                var rowindex = $(this).parent().parent().attr("rowIndex"),
                                                    rowdata = rows[rowindex];
                                                
                                                if (type_ == "linkedit"){
                                                    $(this).parent().click();
                                                }
                                                col.callback.call(grid, { index: rowindex, data: rowdata, cell: this.parentNode });
                                                return false;
                                            });
                                        }
                                    })(col_, $(".grid_action_" + i + "_" + m));
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    
                    //编辑单元格
                    table_body.find(".td_" + m).live(c.dblClickToEdit ? "dblclick" : "click", 
                        function(e){
                            var cont_s = $(this).find(".cont_" + m),
                                cell_type = $(this).attr("cellType"),
                                cell_index = this.cellIndex,
                                row_index = $(this).parent()[0].rowIndex;
                            
                            if (cell_type == "data"){
                                if(c.stopTdTrEvent){
                                    stopBubble(e);
                                }
                                if (cont_s.length > 0){
                                    var colIndex = $(this).attr("colindex");
                                    grid.editCell(row_index, cell_index);
                                }
                            }
                        }
                    ).live("click", function(){
                        var cell_index = this.cellIndex,
                            row_index = $(this).parent()[0].rowIndex;
                        
                        grid.lastClickedCellInfo = {
                            rowIndex: row_index,
                            cellIndex: cell_index 
                        };
                    });
                    
                    //编辑checkbox列
                    grid_ckb.live("click", function(e){
                        var colIndex = $(this).parent().attr("colindex");
                        var rowIndex = $(this).parent().parent().attr("rowIndex");
                        if (c.autoSave){
                            if (c.cellEdited && c.cellEdited instanceof Function){
                                c.cellEdited.call(grid, { field: realColumns_Info.cols[colIndex].field, value: this.checked, data: rows[rowIndex], webGrid: grid });
                            }
                        }
                    });
                },
                createTotalRow = function(c){
                    var arr = [],
                        cols_ = realColumns_Info.cols;
                    
                    arr.push("<table id='table_totalRow_", m, "' cellpadding='0px' cellspacing='0px' style='width:", getLen(), ";table-layout:fixed;border-collapse:collapse;empty-cells:show;'>");
                    arr.push("<tr style='height:", totalRowHeight, "px;background-color:", c.colors.evenRowBgColor, ";'>");
                    if (c.showCheckBox){
                        arr.push("<td style='width:25px;border:none;border-right:dashed 1px " + c.colors.borderColor + ";'></td>");
                    }
                    for(var i=0;i<cols_.length;i++){
                        var col_ = cols_[i],
                            width = "width:" + (col_.width ? /^\d+%$/.test(col_.width) ? col_.width : col_.width + "px" : "auto");
                        arr.push("<td field='" + col_.field + "' style='", width, ";border:none;border-right:dashed 1px " + c.colors.borderColor + ";text-align:" + col_.align + ";'></td>");
                    }
                    arr.push("</tr></table>");
                    table_totalRow = div_totalRow.html(arr.join("")).find("#table_totalRow_" + m);
                    totalRow_first_row_tds = table_totalRow.find("tr:first td")
                },
                createPager = function(c) {
                    var arr = [],
                        show = c.showPagerInfo ? "" : "display:none;";
                    
                    arr.push("<div style='line-height:", pagerHeight, "px;margin-left:4px;float:left;vertical-align:middle;'>");
                    arr.push("<a id='grid_afirst_", m, "' href='javascript:void(0);' style='color:Black;text-decoration:none;'>首页</a>&nbsp;");
                    arr.push("<a id='grid_aprevious_", m, "' href='javascript:void(0);' style='color:Black;text-decoration:none;'>上页</a>&nbsp;");
                    arr.push("<input id='grid_pageindex_", m, "' type='text' style='text-align:center;width:30px;height:13px;font-size:10px;background-color:White;' value='", c.pageIndex, "'/>&nbsp;");
                    arr.push("<a id='grid_anext_", m, "' href='javascript:void(0);' style='color:Black;text-decoration:none;'>下页</a>&nbsp;");
                    arr.push("<a id='grid_alast_", m, "' href='javascript:void(0);' style='color:Black;text-decoration:none;'>尾页</a>");
                    arr.push("</div><div style='margin-top:4px;float:right;margin-right:4px;" + show + "'>");
                    arr.push("共<span style='color:black;' id='grid_spanRow_", m, "'></span>条, ");
                    arr.push("每页<span style='color:black;' id='grid_spanSize_", m, "'></span>条, ");
                    arr.push("共<span style='color:black;' id='grid_spanCount_", m, "'></span>页, ");
                    arr.push("第<span style='color:black;' id='grid_spanIndex_", m, "'></span>页</div>");
                    div_pager.html(arr.join(""));
                    
                    //首页
                    $("#grid_afirst_" + m).click(function() {
                        if (!$(this).attr("disabled") || $(this).attr("disabled") == "false") {
                            grid.gotoPage(1);
                        }
                        return false;
                    });

                    //上页
                    $("#grid_aprevious_" + m).click(function() {
                        if (!$(this).attr("disabled") || $(this).attr("disabled") == "false") {
                            grid.prePage();
                        }
                        return false;
                    });
                    
                    //页数
                    $("#grid_pageindex_" + m).keydown(function(e) {
                        if (e.keyCode == 13) {
                            grid.gotoPage($(this).val());
                        }
                    });

                    //下页
                    $("#grid_anext_" + m).click(function() {
                        if (!$(this).attr("disabled") || $(this).attr("disabled") == "false") {
                            grid.nextPage();
                        }
                        return false;
                    });

                    //尾页
                    $("#grid_alast_" + m).click(function() {
                        if (!$(this).attr("disabled") || $(this).attr("disabled") == "false") {
                            grid.gotoPage(grid.pagerInfo.pageCount);
                        }
                        return false;
                    });
                },
                setPager = function(p) {
                    var grid_afirst = $("#grid_afirst_" + m),
                        grid_aprevious = $("#grid_aprevious_" + m),
                        grid_pageindex = $("#grid_pageindex_" + m),
                        grid_anext = $("#grid_anext_" + m),
                        grid_alast = $("#grid_alast_" + m),
                        grid_spanRow = $("#grid_spanRow_" + m),
                        grid_spanSize = $("#grid_spanSize_" + m),
                        grid_spanCount = $("#grid_spanCount_" + m),
                        grid_spanIndex = $("#grid_spanIndex_" + m);
                    
                    if (p.pageIndex <= 1) {
                        grid_afirst.attr("disabled", "disabled");
                        grid_afirst.css("color", "Gray").css("text-decoration", "none" ).css("cursor", "default" );
                        grid_afirst.removeAttr("href");
                        grid_aprevious.attr("disabled", "disabled");
                        grid_aprevious.css("color", "Gray").css("text-decoration", "none" ).css("cursor", "default" );
                        grid_aprevious.removeAttr("href");
                    }
                    else {
                        grid_afirst.attr("href", "javascript:void(0);").css("color", "Black").css("cursor", "pointer" );
                        grid_aprevious.attr("href", "javascript:void(0);").css("color", "Black").css("cursor", "pointer" );
                        grid_afirst.removeAttr("disabled");
                        grid_aprevious.removeAttr("disabled");
                    }

                    if (p.pageIndex >= p.pageCount) {
                        grid_anext.attr("disabled", "disabled");
                        grid_anext.css("color", "Gray").css("text-decoration", "none" ).css("cursor", "default" );
                        grid_anext.removeAttr("href");
                        grid_alast.attr("disabled", "disabled");
                        grid_alast.css("color", "Gray").css("text-decoration", "none" ).css("cursor", "default" );
                        grid_alast.removeAttr("href");
                    }
                    else {
                        grid_anext.attr("href", "javascript:void(0);").css("color", "Black").css("cursor", "pointer" );
                        grid_alast.attr("href", "javascript:void(0);").css("color", "Black").css("cursor", "pointer" );
                        grid_anext.removeAttr("disabled");
                        grid_alast.removeAttr("disabled");
                    }

                    grid_pageindex.val(p.pageIndex);
                    grid_spanRow.text(p.rowCount);
                    grid_spanSize.text(p.pageSize);
                    grid_spanCount.text(p.pageCount);
                    grid_spanIndex.text(p.pageIndex);
                },
                setHeader = function(){
                    if (table_body){
                        var h_w = table_header.css("width"),
                            width = div_body[0].clientWidth;
                        
                        $("#checkall_" + m).attr("checked", false);
                        div_header.css({ "width": width + "px" });
                        div_totalRow.css({ "width": width + "px" });
                        table_body.css("width", h_w);
                        table_totalRow.css("width", h_w);
                        header_first_row_tds.each(function(i, o_){
                            var c_width = grid.loaded ? o_.style.pixelWidth : o_.clientWidth;
                            $(body_first_row_tds[i]).css("width", c_width + "px");
                            $(totalRow_first_row_tds[i]).css("width", c_width + "px");
                            $(o_).css("width", c_width + "px");
                        });
                    }
                };
            
            this.M = m;
            this.loaded = false;
            this.lastClickedCellInfo = { rowIndex: -1, cellIndex: -1 };
            this.refreshReasonList = refresh_reason_s;
            this.currentRowIndex = -1;
            this.pagerInfo = {};
            this.dataRows = [];
            this.config;
            
            //下页
            this.nextPage = function(){
                return grid.gotoPage(c.pageIndex + 1);
            };
            
            //上页
            this.prePage = function(){
                return grid.gotoPage(c.pageIndex - 1);
            };
            
            //页数
            this.gotoPage = function(index){
                if (c.pager){
                    index = parseInt(index);
                    index = !isNaN(index) ? index : c.pageIndex;
                    index = index < 1 ? 1 : index > grid.pagerInfo.pageCount ? grid.pagerInfo.pageCount : index;
                    if (index != c.pageIndex){
                        refresh_reason = refresh_reason_s.newPage;
                        c.pageIndex = index;
                        grid.refresh();
                        
                        if (c.isCookie){
                            cookie("pageindex_" + c.contentId, c.pageIndex);
                        }
                    }
                    else{
                        setPager(grid.pagerInfo);
                    }
                }
                return grid;
            };
            
            this.removeRow = function(index_){
                index_ = isNaN(parseInt(index_)) ? 0 : parseInt(index_) < 0 ? 0 : parseInt(index_);
                $("#table_body_" + m + " tr:eq(" + index_ + ")").remove();
                rows = removeArrayAt(rows, index_);
                if (rows.length == 0){
                    createBody(c);
                }
                grid.dataRows = rows;
                table_body = div_body.css("height", c.autoHeight ? 
                    (table_body[0].clientHeight + 17) + "px"
                        : div_body.css("height")).find("#table_body_" + m);
                body_first_row_tds = table_body.find("tr:first td");
                setRows_();
                setHeader();
                return grid;
            };
            
            this.addNewRow = function(index_, pos_, data_){
                index_ = isNaN(parseInt(index_)) ? 0 : parseInt(index_) < 0 ? 0 : parseInt(index_);
                pos_ = pos_ ? pos_.toLowerCase() : "before";
                
                var newRowData = function(data){
                        data = data || {};
                        var obj = function(cols){
                                if (rows.length > 0){
                                    return rows[0];
                                }
                                else{
                                    var o_ = {};
                                    for(var i=0;i<cols.length;i++){
                                        o_[cols[i].field] = "";
                                    }
                                    return o_;
                                }
                            }(realColumns_Info.cols);
                        
                        for(var it in obj){
                            if (!data[it]){
                                data[it] = "";
                            }
                        }
                        return data;
                    }(data_),
                    tr_ = function(){
                        var flag_ = pos_ == "before" && index_ == 0;
                        if (flag_){
                            $("#table_body_" + m + " tr:eq(0) td").css("width", "auto");
                        }
                        return createRow(newRowData, $("#table_body_" + m + " tr").length, flag_, true);
                    }();
                
                if (rows.length == 0){
                    $("#table_body_" + m).html(tr_);
                    rows = insertArrayAt(rows, newRowData, 0);
                }
                else{
                    if (pos_ == "before"){
                        rows = insertArrayAt(rows, newRowData, index_);
                        $("#table_body_" + m + " tr:eq(" + index_ + ")").before(tr_);
                        
                    }
                    else if(pos_ == "after"){
                        rows = insertArrayAt(rows, newRowData, index_ + 1);
                        $("#table_body_" + m + " tr:eq(" + index_ + ")").after(tr_);
                    }
                }
                grid.dataRows = rows;
                
                table_body = div_body.css("height", c.autoHeight ? 
                    (table_body[0].clientHeight + 17) + "px"
                        : div_body.css("height")).find("#table_body_" + m);
                body_first_row_tds = table_body.find("tr:first td");
                setRows_();
                setHeader();
                return grid;
            }
            
            this.toSelectRow = function(index){
                index = isNaN(index) ? 0 : index;
                var table_body = $("#table_body_" + m);
                if (rows.length > 0){
                    var row = table_body.find("tr:eq(" + index + ")");
                    if (c.multiSelect) {
                        if (row.attr("selected_") != "1") {
                            row.click();
                        }
                    }
                    else {
                        row.click();
                    }
                }
                return grid;
            };
            
            this.toSelectAll = function(){
                if (c.multiSelect) {
                    var checkall = $("#checkall_" + m);
                    checkall.attr({ "checked": true });
                    checkall.click();
                    checkall.attr({ "checked": true });
                }
                return grid;
            };
            
            this.toSelectNone = function(){
                if (c.multiSelect) {
                    var checkall = $("#checkall_" + m);
                    checkall.attr({ "checked": false });
                    checkall.click();
                    checkall.attr({ "checked": false });
                }
                return grid;
            };
            
            this.resizeTo = function(size){
                if (size.width) {
                    content.css({ "width": size.width + "px" });
                }
                if (!c.autoHeight && size.height) {
                    content.css({ "height": size.height + "px" });
                }
                var w_ = content[0].clientWidth - (c.is3D ? c.borderWidth3D * 2 : 2),
                    h_ = content[0].clientHeight - (c.is3D ? c.borderWidth3D * 2 : 2) - (c.showTotalRow ? 3 : 2);
                
                contentWidth = w_ < 0 ? 0 : w_;
                contentHeight = h_ < 0 ? 0 : h_;
                var bodyHeight = c.autoHeight ? "auto" 
                    : (c.pager ? 
                        c.showTotalRow ? contentHeight - headerHeight - pagerHeight - totalRowHeight : contentHeight - headerHeight - pagerHeight 
                            : c.showTotalRow ? contentHeight - headerHeight - totalRowHeight : contentHeight - headerHeight) + "px";
                div_headerMain.css({ "width": contentWidth + "px" });
                div_totalRowMain.css({ "width": contentWidth + "px" });
                div_pager.css({ "width": contentWidth + "px" });
                div_body.css({ "width": contentWidth + "px" });
                if (!c.autoHeight){
                    div_body.css({ "height": bodyHeight });
                }
                setHeader();
                
                return grid;
            };
            
            //获取选中行的数据
            this.selectedRows = function(){
                var arr = [],
                    rows = grid.selectedRowsEx();
                for(var i=0; i< rows.length; i++){
                    arr.push(rows[i].data);
                }
                return arr;
            };
            
            //获取选中行的索引及数据
            this.selectedRowsEx = function(){
                var arr = [],
                    TRs = $("#table_body_" + m).find("tr");
                for(var i=0; i < TRs.length; i++){
                    if (TRs[i].getAttribute("selected_") == "1"){
                        arr.push({ index: i, data: rows[i] });
                    }
                }
                return arr;
            };
            
            //获取所有被编辑过且数据改变了的行数据
            this.changedRows = function(){
                var arr_update = [],
                    cols_ = realColumns_Info.cols,
                    trs = $("#table_body_" + m + " tr");
                
                for(var i=0; i< trs.length; i++){
                    var new_ = $(trs[i]).attr("new"),
                        tds = $(trs[i]).children("td"),
                        obj = { index: i, data: {} },
                        changedCount = 0,
                        row_data = function(row){
                            var obj_row = {};
                            for(var it in row){
                                obj_row[it] = row[it];
                            }
                            return obj_row;
                        }(grid.dataRows[i]);
                    
                    if (new_ == "new"){
                        for(var j=0; j< tds.length; j++){
                            
                        }
                    }
                    else{
                        for(var j=0; j< tds.length; j++){
                            var cont_ = $(tds[j]).children("[tag='tag_" + m + "']"),
                                field = $(tds[j]).attr("field"),
                                colindex = $(tds[j]).attr("colindex");
                            
                            if (field && field != ""){
                                var coltype = cols_[colindex].type.toLowerCase();
                                if (coltype == "data" || coltype == "linkedit"){
                                    var val = unescape(cont_.attr("val"));
                                    if (val != rows[i][field]){
                                        row_data[field] = { val: val, changed: true };
                                        obj.data = row_data;
                                        changedCount ++;
                                    }
                                }
                                else if (coltype == "checkbox"){
                                    var ckb = $(tds[j]).children(":checkbox"),
                                        checked = ckb.attr("checked");
                                    if ((checked && ckb.attr("val") != "1") || (!checked && ckb.attr("val") != "0")){
                                        row_data[field] = { val: (checked ? "1" : "0"), changed: true };
                                        obj.data = row_data;
                                        changedCount ++;
                                    }
                                }
                            }
                        }
                        
                        if (changedCount > 0){
                            arr_update.push(obj);
                        }
                    }
                }
                
                var obj = objToXML(arr_update);
                return { json: arr_update, xml: obj.xml, xmlString: obj.xmlString };
            };
            
            this.setCellText = function(row_, col_, txt_){
                var cols_ = realColumns_Info.cols,
                    cell_ = table_body.find(".tr_" + m + ":eq(" + row_ + ") td:eq(" + col_ + ")"),
                    col_index = cell_.attr("colindex"),
                    col_ = cols_[col_index],
                    val_ = txt_ || "";
                
                txt_ = val_ == "" ? (col_.type == "linkedit" ? c.linkEditDefaultText : val_) : val_;
                cell_.attr("title", val_).find("[tag='tag_" + m + "']").text(txt_).attr("val", escape(val_));
            };
            
            this.getCellText = function(row_, col_){
                var cell_ = table_body.find(".tr_" + m + ":eq(" + row_ + ") td:eq(" + col_ + ")");
                return decodeHtml(brTo_n(unescape(cell_.find("[tag='tag_" + m + "']").attr("val"))));
            };
            
            this.setTotalRowTextByField = function(field_, txt_){
                if (field_){
                    txt_ = txt_ || "";
                    totalRow_first_row_tds.each(function(i, td){
                        var f = $(td).attr("field");
                        if (f == field_){
                            $(td).attr("title", txt_).text(txt_);
                        }
                    });
                }
                return grid;
            };
            
            this.setTotalRowTextByIndex = function(index_, txt_){
                txt_ = txt_ || "";
                $(totalRow_first_row_tds[index_]).attr("title", txt_).text(txt_);
                return grid;
            };
            
            //编辑单元格的方法
            this.editCell = function(rowindex, cellindex){
                if (arguments.length == 2  && !isNaN(rowindex) && !isNaN(cellindex)){
                    var cols_ = realColumns_Info.cols,
                        cell = $("#table_body_" + m + " tr:eq(" + rowindex + ") td:eq(" + cellindex + ")"),
                        cont_ = cell.children(".cont_" + m),
                        colIndex = cell.attr("colindex"),
                        col_ = cols_[colIndex];
                    
                    if (col_.editable && cell.attr("editing") != "1"){
                        cell.attr({ "editing": "1" });
                        var width = cell[0].clientWidth,
                            height = cell[0].clientHeight,
                            editer = col_.editer,
                            type_ = editer.type.toLowerCase();
                        
                        switch(type_){
                            case "text":
                                if (c.rowMultiLine){
                                    cont_.html("<textarea class='editer_" + m + "' style='overflow-y:auto;font-size:" + c.fontSize + 
                                        "px;width:" + (width - 7) + "px;height:" + (height < 48 ? 40 : height - 8) + "px;'></textarea>");
                                }
                                else{
                                    cont_.html("<input class='editer_" + m + "' type='text'  style='font-size:" + c.fontSize + 
                                        "px;width:" + (width - 7) + "px;'/>");
                                }
                                cont_.find(".editer_" + m).val(decodeHtml(brTo_n(unescape(cont_.attr("val")))));
                                break;
                            case "select":
                                var arr = [];
                                if (editer.items.length > 0){
                                    if (editer.valField != "" && editer.txtField != ""){
                                        for(var i=0;i< editer.items.length; i++){
                                            var txt = editer.items[i][editer.txtField],
                                                val = editer.items[i][editer.valField];
                                            
                                            arr.push("<option value='" + val + "'>" + txt + "</option>");
                                        }
                                    }
                                }
                                cont_.html("<select class='editer_" + m + "' style='font-size:" + c.fontSize + "px;width:" + width + "px;'>" + arr.join("") + "</select>");
                                break;
                            default:
                                break;
                        }
                        
                        cont_.find(".editer_" + m).blur(function(e){
                            grid.endEditCell(rowindex, cellindex);
                        }).keydown(function(e){
                            if (e.keyCode == 13){
                                if (this.tagName.toLowerCase() != "textarea"){
                                    grid.endEditCell(rowindex, cellindex);
                                }
                            }
                        }).click(stopBubble).focus().select();
                        div_body.scroll().css("height", c.autoHeight ? 
                            (table_body[0].clientHeight + 17) + "px"
                                : div_body.css("height"));
                    }
                }
                
                return grid;
            };
            
            this.endEditCell = function(rowindex, cellindex){
                if (arguments.length == 2  && !isNaN(rowindex) && !isNaN(cellindex)){
                    var cols_ = realColumns_Info.cols,
                        cell = $("#table_body_" + m + " tr:eq(" + rowindex + ") td:eq(" + cellindex + ")"),
                        cont_ = cell.children(".cont_" + m),
                        colIndex = cell.attr("colindex"),
                        col_ = cols_[colIndex];
                    
                    if (col_.editable && cell.attr("editing") == "1"){
                        var editer_ = cont_.find(".editer_" + m),
                            val_ = editer_.val(),
                            str = col_.format ? 
                                col_.format(val_,
                                    _nToBr(encodeHtml(val_.replace(/&/g, "&amp;"))),
                                    _nToBr(val_.replace(/&/g, "&amp;")),
                                    _nToBr(encodeHtml(val_).replace(/&/g, "&amp;"))
                                ) 
                                : _nToBr(encodeHtml(val_.replace(/&/g, "&amp;")));
                        
                        cell.attr({ "editing": "0" });
                        cont_.html(str == "" ? "&nbsp;" : str);
                        if (c.autoSave){
                            var flag = false;
                            if (c.cellEdited && c.cellEdited instanceof Function){
                                flag = c.cellEdited.call(grid, { field: col_.field, value: val_, data: rows[rowindex], webGrid: grid, target: editer_[0], index: rowindex });
                            }
                            if (flag) {
                                cell.attr({ "title": val_ });
                                cont_.attr("val", val_);
                                rows[rowindex][cell.attr("field")] = val_;
                                if (c.cellEditSuccess && c.cellEditSuccess instanceof Function){
                                    c.cellEditSuccess.call(grid, { field: col_.field, value: val_, data: rows[rowindex], webGrid: grid, target: editer_[0], index: rowindex });
                                }
                            }
                            else{
                                var val = unescape(cont_.attr("val"));
                                str = col_.format ? 
                                    col_.format(val,
                                        _nToBr(encodeHtml(val.replace(/&/g, "&amp;"))),
                                        _nToBr(val.replace(/&/g, "&amp;")),
                                        _nToBr(encodeHtml(val).replace(/&/g, "&amp;"))
                                    ) 
                                    : _nToBr(encodeHtml(val.replace(/&/g, "&amp;")));
                                cont_.html(str == "" ? "&nbsp;" : str);
                                if (c.cellEditError && c.cellEditError instanceof Function){
                                    c.cellEditError.call(grid, { field: col_.field, value: val_, data: rows[rowindex], webGrid: grid, target: editer_[0], index: rowindex });
                                }
                            }
                        }
                        else {
                            cell.attr({ "title": val_ });
                            cont_.attr("val", val_);
                        }
                        div_body.css("height", c.autoHeight ? 
                            (table_body[0].clientHeight + 17) + "px"
                                : div_body.css("height"));
                    }
                }
            };
            
            //刷新数据部分
            this.refresh = function(){
                if (c.beforeRefresh && c.beforeRefresh instanceof Function){
                    c.beforeRefresh.call(grid, { webGrid: grid, refreshReason: refresh_reason });
                }
                
                grid.currentRowIndex = -1;
                getData(c, (arguments[0] ? [] : null));
                createBody(c);
                setPager(grid.pagerInfo);
                setHeader();
                
                div_body.scroll(function() {
                    var left = $(this).scrollLeft();
                    div_header.scrollLeft(left);
                    div_totalRow.scrollLeft(left);
                }).scroll();
                
                refresh_reason = refresh_reason_s.other;
                if (c.afterRefresh && c.afterRefresh instanceof Function){
                    c.afterRefresh.call(grid, { webGrid: grid, refreshReason: refresh_reason });
                }
                
                return grid;
            };
            
            this.load = function(){
                refresh_reason = refresh_reason_s.load;
                createContent(c); createHeader(c); createPager(c); createTotalRow(c); grid.refresh(!c.autoRefresh);
                if (c.afterLoad && c.afterLoad instanceof Function){
                    c.afterLoad.call(grid, { webGrid: grid });
                }
                
                grid.loaded = true;
                return grid;
            };
            
            if (c.autoLoad){
                grid.load();
            }
        }
    });
    
})(jQuery);